package Views;

import Source.LoginUser;
import UCM.UCLoginUser;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;

/**
 * A view of login user
 * @author Josh
 */
public class ViewLoginUser extends JPanel {

    private final int maxChar = 10;
    private MainUI mainView;
    private final UCLoginUser UCLogin = new UCLoginUser(this);
    private LoginUser model;
    private JPanel loginPanel = new JPanel();
    private JTextField userField = new JTextField(maxChar);
    private JPasswordField passwordField = new JPasswordField(maxChar);
    private JButton loginButton = new JButton("Login");
    private JButton logoutButton = new JButton("Logout");
    private JLabel loggedInLabel = new JLabel();
    private JPanel loginFailurePanel = new JPanel();
    private JLabel loginFailureLabel = new JLabel("Login Unsuccessful.");
    private JPanel loginSuccessPanel = new JPanel();
    private JLabel loginSuccessLabel = new JLabel("Login Successful.");

    /**
     * Construction that initualises the variables for the login user view
     * @param mainView
     */
    public ViewLoginUser(MainUI mainView) {

        this.mainView = mainView;
        this.add(loginPanel);
        loginPanel.add(userField);
        loginPanel.add(passwordField);
        loginPanel.add(loginButton);
        loginPanel.setLayout(new FlowLayout());
        loginButton.addActionListener(new AdapterUCCToAL(UCLogin));
        passwordField.setEchoChar('*');
        this.setVisible(true);
    }

    /**
     * loads the model to the view
     * @param model
     */
    public void loadTo(LoginUser model) {
        this.model = model;
    }

    /**
     * gets the user field
     * @return
     */
    public String getUserField() {
        return userField.getText();
    }

    /**
     * gets the password field
     * @return
     */
    public char[] getPasswordField() {
        return passwordField.getPassword();
    }

    /**
     * Update the ui to indicate failure
     */
    public void updateUIFailure() {
        mainView.removeCenterPanel();
        mainView.add(loginFailurePanel, BorderLayout.CENTER);
        loginFailurePanel.add(loginFailureLabel);
        mainView.pack();
    }

    /**
     * Updates the ui to indicate failure
     * @param user
     */
    public void updateUISuccess(String user) {
        mainView.removeCenterPanel();
        mainView.add(loginSuccessPanel, BorderLayout.CENTER);
        loginSuccessPanel.add(loginSuccessLabel);
        loginPanel.remove(userField);
        loginPanel.remove(passwordField);
        loginPanel.remove(loginButton);
        loginPanel.add(loggedInLabel);
        loggedInLabel.setText(user);
        loginPanel.add(logoutButton);
        mainView.addDeleteButton();
        mainView.pack();
    }
}
